package com.dobby.htmlunit.demo.omqq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.net.URL;
import java.util.*;

/**
 * 企鹅自媒体渠道同步
 * Created by jonas on 2017/2/6.
 */
public class OmqqPoster {

    private static WebClient webClient = null;

    private String cookie = null;

    public OmqqPoster() {
    }

    private OmqqPoster(String cookie) {
        this.cookie = cookie;
    }

    private static WebClient getWebClient() {
        if(webClient == null) {
            webClient = new WebClient();
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setRedirectEnabled(true);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.waitForBackgroundJavaScript(10000);
            webClient.getOptions().setTimeout(10000);
        }
        return webClient;
    }

    public static OmqqPoster addCookie(String cookie) {
        if(StringUtils.isNotBlank(cookie)) {
            return new OmqqPoster(cookie);
        }
        return new OmqqPoster();
    }

    private WebRequest addHeaders(WebRequest request) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept","application/json, text/javascript, */*; q=0.01");
        headers.put("accept-encoding","gzip, deflate");
        headers.put("accept-language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("content-type","application/x-www-form-urlencoded; charset=UTF-8");
        headers.put("origin","https://om.qq.com");
        headers.put("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        headers.put("x-requested-with","XMLHttpRequest");
        if(null != this.cookie) {
            headers.put("cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        request.setAdditionalHeaders(headers);
        return request;
    }

    private WebRequest addFileHeaders(WebRequest request) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("accept","*/*");
        headers.put("accept-encoding","gzip, deflate");
        headers.put("accept-language","zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4");
        headers.put("content-type","multipart/form-data");
        headers.put("origin","https://om.qq.com");
        headers.put("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
        if(null != this.cookie) {
            headers.put("cookie", this.cookie);
        } else {
            throw new Exception("缺少cookie信息");
        }
        request.setAdditionalHeaders(headers);
        return request;
    }

       public String updateArticle(String title, String content) throws Exception {
        String url = "https://om.qq.com/editorCache/update?relogin=1";
        WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);
        request.setCharset("UTF-8");
        addHeaders(request);
        // 添加请求参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("title", title));
        params.add(new NameValuePair("content", content));
        params.add(new NameValuePair("category_id", "40"));  // 默认指定一个分类：鸡汤
        params.add(new NameValuePair("cover_type", "-1"));
        request.setRequestParameters(params);

        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();

        JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
        System.out.println("企鹅自媒体 |||| 更新文章 ===》" + jsonObject.toJSONString());

        return null;
    }


    /**
     * 保存为草稿
     * @param title
     * @param content
     * @return 文章id
     * @throws Exception
     *    code -10403 cookie不正确
     *    code 0    save success
     */
    public String saveDraft(String title, String content) throws Exception {

        String url = "https://om.qq.com/article/save?relogin=1";
        WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);
        request.setCharset("UTF-8");
        addHeaders(request);
        // 添加请求参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("title", title));
        params.add(new NameValuePair("content", content));
        params.add(new NameValuePair("category_id", "40"));  // 默认指定一个分类：鸡汤
        params.add(new NameValuePair("cover_type", "-1"));
        params.add(new NameValuePair("type", "0"));
        params.add(new NameValuePair("apply_olympic_flag", "0"));
        params.add(new NameValuePair("apply_push_flag", "0"));
        params.add(new NameValuePair("apply_reward_flag", "1"));
        request.setRequestParameters(params);

        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();

        JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
        System.out.println("企鹅自媒体 |||| 保存草稿 ===》" + jsonObject.toJSONString());

        JSONObject response = (JSONObject) jsonObject.get("response");
        Integer code = response.getInteger("code");
        if(code == -10403) {  // cookie 不正确
            throw new Exception("cookie不正确");
        }
        if(code == 0) {
            System.out.println("=====================企鹅自媒体 |||| 保存草稿成功！======================");
            JSONObject data = (JSONObject) jsonObject.get("data");
            String articleId = data.getString("articleId");
            return articleId;
        }
        System.out.println("=====================企鹅自媒体 |||| 保存草稿出现错误！======================");
        return null;
    }


    /**
     * 快速发布，先存草稿再发布
     * @param articleId
     * @return
     * @throws Exception
     */
    public String quickPublish(String articleId) throws Exception {
        String url = "https://om.qq.com/article/quickPublish?relogin=1";
        WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);
        request.setCharset("UTF-8");
        addHeaders(request);
        // 添加请求参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("articleId", articleId));
        request.setRequestParameters(params);

        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();
        JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
        System.out.println("企鹅自媒体 |||| 快速发布 =====》" + jsonObject.toJSONString());

        JSONObject response = (JSONObject) jsonObject.get("response");
        Integer code = response.getInteger("code");
        if(code == -10403) {  // cookie 不正确
            throw new Exception("cookie不正确");
        }
        if(code == -50122) {  // 已发布成功，不要重复发布
            throw new Exception("文章已发布,不能重复发布");
        }
        if(code == -5005) {
            throw new Exception("标题重复");
        }
        if(code == -5002) {
            throw new Exception("每日发文不能超过5篇");
        }
        if(code == 0) {  // 成功
            System.out.println("=====================企鹅自媒体 |||| 快速发布文章成功！======================");
            JSONObject data = (JSONObject) jsonObject.get("data");
            String fUrl = ((JSONObject) data.get("article")).getString("Furl");
            if(StringUtils.isNotBlank(fUrl)) {
                return fUrl;
            }
        }
        System.out.println("=====================企鹅自媒体 |||| 快速发布文章出现错误！======================");
        return null;
    }


    /**
     * 先保存为草稿再发布文章
     * @param title
     * @param content
     * @return
     * @throws Exception
     */
    public String saveDraftAndPublish(String title, String content) throws Exception {
        String articleId = saveDraft(title, content);
        System.out.println(articleId);
        String fUrl = quickPublish(articleId);
        System.out.println(fUrl);
        return fUrl;
    }



    public Map<String, Object> getStatInfo(String articleId) throws Exception {
        Integer commentNum = 0;
        int max = Integer.MAX_VALUE;
        String url = "https://om.qq.com/article/list?num=" + max;
        WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
        request.setCharset("UTF-8");
        addHeaders(request);

        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();
        JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
        JSONObject response = (JSONObject) jsonObject.get("response");
        Integer code = response.getInteger("code");
        if(code.equals(0)) {
            JSONObject data = (JSONObject) jsonObject.get("data");
            JSONArray articles = (JSONArray) data.get("articles");

            for(Iterator iterator = articles.iterator(); iterator.hasNext(); ) {
                JSONObject article = (JSONObject) iterator.next();
                if(article.getString("article_id").equals(articleId)) {
                    commentNum = article.getInteger("commentnum");
                    break;
                }
            }
            System.out.println("commentNum:" + commentNum);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("commentNum", commentNum);
            return map;
        }
        return null;
    }


    /**
     * FIXME 上传图片不成功， htmlunit 的 请求 无法传递 File类型
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadImage(File file) throws Exception {
        String url = "https://om.qq.com/image/archscaleupload?isRetImgAttr=1&relogin=1";
        WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);
        request.setCharset("UTF-8");
        addFileHeaders(request);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("id", "WU_FILE_0"));
        params.add(new NameValuePair("name", file.getName()));
        params.add(new NameValuePair("type", "image/jpeg"));
        params.add(new NameValuePair("lastModifiedDate", new Date().toString()));
        params.add(new NameValuePair("Filename", file.getName()));
        params.add(new NameValuePair("Filedata", file.toString()));
        request.setRequestParameters(params);


        JSONObject json = new JSONObject();
        json.put("id", "WU_FILE_0");
        json.put("name", file.getName());
        json.put("Filename", file.getName());
        json.put("Filedata", file);
        request.setRequestBody(json.toJSONString());


        Page page = getWebClient().getPage(request);
        WebResponse webResponse = page.getWebResponse();
        String jsonInfo = webResponse.getContentAsString();
        JSONObject jsonObject = JSONObject.parseObject(jsonInfo);
        System.out.println(jsonObject.toJSONString());

        return null;
    }

}
